import { createRouter, createWebHashHistory } from 'vue-router'
import storage from '../utils/storage'

const routes = [
  { path: '/', name: 'home', component: () => import('../views/home/Home.vue') },
  { path: '/login', name: 'login', component: () => import('../views/login/Login.vue') },
  { path: '/register', name: 'register', component: () => import('../views/register/Register.vue') },
  { path: '/my', name: 'my', component: () => import('../views/my/My.vue') }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const token = storage.getItem('token') || ''
  const isLogin = !!token
  if (isLogin) {
    // 如果已经登录
    to.name === 'login' || to.name === 'register' ? next('/') : next()
  } else {
    to.name === 'login' || to.name === 'register' ? next() : next('/login')
  }
})

export default router
